package com.tenbent.product.center.user.service.impl;

//import com.tenbent.product.base.exception.TenbentNotFoundException;
import com.tenbent.product.base.exception.TenbentException;
import com.tenbent.product.base.security.impl.CustomUserDetailsServiceImpl;
//import com.tenbent.product.base.service.impl.BaseServiceImpl;
//import com.tenbent.product.center.role.bo.Role;
import com.tenbent.product.center.cache.PermCacheService;
//import com.tenbent.product.center.role.service.RoleService;
import com.tenbent.product.center.user.bo.User;
//import com.tenbent.product.center.user.bo.UserRole;
import com.tenbent.product.center.user.mapper.UserMapper;
//import com.tenbent.product.center.user.service.UserRoleService;
import com.tenbent.product.center.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.GrantedAuthority;
//import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

//import java.util.ArrayList;
import java.util.List;

/**
 * 用户服务层，security的实现
 *
 * Created by ThinkPad on 2017/8/31.
 */
@Service(value = "userServiceImpl")
public class UserServiceImpl extends CustomUserDetailsServiceImpl<User> implements UserService {
	// BaseServiceImpl<User> implements UserService {

	private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

	public UserServiceImpl() {
		this.setClazz(User.class);
	}

	@Autowired
	private UserMapper userMapper;

	// @Autowired
	// @Qualifier("roleServiceImpl")
	// private RoleService roleService;
	//
	// @Autowired
	// @Qualifier("userRoleServiceImpl")
	// private UserRoleService userRoleService;

	@Autowired
	@Qualifier("permCacheServiceImpl")
	private PermCacheService permCacheService;

	@Override
	public UserDetails loadUserByUsername(String ssoId) throws UsernameNotFoundException {

		User user = new User();
		user.setLoginId(ssoId);
		List<User> users = this.queryObj(user);
		if (users == null || users.isEmpty()) {
			throw new UsernameNotFoundException("用户不存在！");
		}
		user = users.get(0);
		return new org.springframework.security.core.userdetails.User(user.getLoginId(), user.getPassword(),
				getGrantedAuthorities(user));

	}

	@Override
	public User save(User user) {
		this.add(user);
		return user;
	}

	/**
	 * 根据用户获取用户对应角色
	 *
	 * @param user
	 *            登录用户
	 */
	private List<GrantedAuthority> getGrantedAuthorities(User user) {
		// //方式一（非数据库方式）
		// List<GrantedAuthority> authorities = new ArrayList<>();
		// authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
		// return authorities;

		// //方式二（数据库方式）
		// UserRole query = new UserRole();
		// query.setUserId(user.getId());
		// List<UserRole> userRoles = userRoleService.queryObj(query);
		// if (userRoles == null || userRoles.isEmpty()) {
		// throw new TenbentNotFoundException("无法获取用户对应权限！");
		// }
		// List<GrantedAuthority> authorities = new
		// ArrayList<>(userRoles.size());
		// for (UserRole userRole : userRoles) {
		// Role role = roleService.getByKey(userRole.getRoleId());
		// authorities.add(new SimpleGrantedAuthority(role.getRoleCode()));
		// }
		// return authorities;

		// //方式三（数据库+缓存方式）
		try {
			return permCacheService.getGrantedAuthorities(user);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("获取登录用户权限异常, 原因: {}", e.getMessage());
			throw new TenbentException(500, "the perm of user is error!");
		}
	}
}
